#include "Logger.h"
#include "Config.h"
#include "LockFile.h"
#include <fstream>
#include <sstream>


std::string Logger::m_ProcessInf = "Generic Process N- X:";
std::string Logger::m_LogName = "Log.txt";
int Logger::log_level = 4;

Logger& Logger::getInstance() {
	/* Variable instantiated in the first use, destroyed 
	 *  automatically in the end of the program
	 */
		static Logger m_Instance;
		return m_Instance;
	}

void Logger::init()
{
	log_level = Config::get_instance().get_int("log_level");
}

void Logger::createLog(const std::string i_LogName) {
	if (! i_LogName.empty()) {
		m_LogName = i_LogName;
	}
	init();
	Logger::getInstance().writeMessageInLog(
	"LogFile created succesfully\n\n", std::ios::out | std::ios::trunc);
}		

void Logger::logMessage(LogLevelEnum i_Level, std::string i_Msg) {
	if(i_Level <= log_level){
		LockFile file = LockFile(m_LogName.c_str());
		std::stringstream ss;
		ss << i_Level <<  " " << m_ProcessInf << " " << i_Msg << std::endl;

		file.takeLock();
		file.writeToFile(ss.str().c_str(), ss.str().length());
		file.releaseLock();
	}
}

void Logger::writeMessageInLog(std::string i_LogMsg, std::ios_base::openmode i_OpenMode) {
	std::ofstream logFile; 
	logFile.open(m_LogName.c_str(), i_OpenMode);

	if (logFile.good())
	{
		logFile << i_LogMsg;
	}		

	logFile.close();
}

void Logger::setProcessInformation(const std::string i_ProcessInformation) {
	m_ProcessInf = i_ProcessInformation;
}
